package tk.hongbo.srlogin

import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import tk.hongbo.srlogin.databinding.FragmentSrLoginBinding

private const val ARG_PARAM_APPID = "arg_param_appid"
private const val ARG_PARAM_AGENTID = "arg_param_agentid"
private const val ARG_PARAM_REDIRECT_URI = "arg_param_redirect_uri"

/**
 * 企业微信扫码登录
 */
class SrLoginFragment : Fragment() {

    private lateinit var binding: FragmentSrLoginBinding
    private var webView: WebView? = null

    private var paramAppId: String? = null
    private var paramAgentId: String? = null
    private var paramRedirectUri: String? = null

    private var callListener: OnListener? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            paramAppId = it.getString(ARG_PARAM_APPID)
            paramAgentId = it.getString(ARG_PARAM_AGENTID)
            paramRedirectUri = it.getString(ARG_PARAM_REDIRECT_URI)
        }
    }

    override fun onStart() {
        super.onStart()
        loadUrl()
    }

    fun reload() {
        loadUrl()
    }

    private fun loadUrl() {
        //webView.loadUrl("https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=wwf4aa38a5736fae51&agentid=1000002&redirect_uri=http%3A%2F%2Fwww.huangbaoche.com&state=web_login%40gyoss9")
        webView?.loadUrl("https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=${paramAppId}&agentid=${paramAgentId}&redirect_uri=http%3A%2F%2F${paramRedirectUri}&state=web_login%40gyoss9")
    }

    //http://www.huangbaoche.com/?code=darHo01DGGOVAYaFdMcTSETrT66cn_gxowij7AYHVpU&state=web_login@gyoss9&appid=ww27056243634bc86a
    private fun success(url: Uri) {
        val code = url.getQueryParameter("code")
        callListener?.callback(code)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        if (container != null) {
            binding = FragmentSrLoginBinding.inflate(
                LayoutInflater.from(container.context),
                container,
                false
            )
            //添加WebView
            webView = WebView(container.context)
            setWebview(webView)
            webView?.layoutParams = FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            )
            binding.root.removeAllViews()
            binding.root.addView(webView)
        }
        return binding.root
    }

    private fun setWebview(webview: WebView?) {
        webview?.settings?.javaScriptEnabled = true
        webview?.settings?.useWideViewPort = true
        webview?.settings?.loadWithOverviewMode = true
        webview?.setInitialScale(10) //缩放网页，调用更好适配
        webview?.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                val uri = Uri.parse(url)
                if (uri.authority.equals(paramRedirectUri)) {
                    success(uri)
                } else {
                    webview?.loadUrl(url.toString())
                }
                return true
            }
        }
    }

    companion object {
        @JvmStatic
        fun newInstance(paramAppId: String, paramAgentId: String, paramRedirectUri: String) =
            SrLoginFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM_APPID, paramAppId)
                    putString(ARG_PARAM_AGENTID, paramAgentId)
                    putString(ARG_PARAM_REDIRECT_URI, paramRedirectUri)
                }
            }
    }

    override fun onAttach(context: Context) {
        if (context is OnListener) {
            callListener = context
        } else {
            throw IllegalAccessError("Not SrLoginFragment.OnListener")
        }
        super.onAttach(context)
    }

    override fun onDestroy() {
        binding.root.removeAllViews()
        super.onDestroy()
    }

    interface OnListener {
        fun callback(code: String?)
    }
}